import { dataSource } from "../../db/typeorm";
import { validatorData } from "../../db/utils";
import { Task, TaskUser } from "../../entity/task";
import { TaskCategory, TaskCategoryPerm } from "../../entity/task_category";
import { formatPageFileterData } from "../../utils/pages";

export function taskPage({ user_id }: { user_id?: string | number }) {}

// 创建任务分类
export async function taskCategoryCreate(data: any, user_id: number | string) {
  const taskCategoryInfo = formatPageFileterData(data, [
    "category_name",
    "category_describe",
  ]) as unknown as Task;
  taskCategoryInfo.create_user = Number(user_id);
  await validatorData(taskCategoryInfo, TaskCategory);

  await dataSource.transaction(async (transactionalEntityManager) => {
    const result = await transactionalEntityManager
      .getRepository(TaskCategory)
      .insert(taskCategoryInfo);
    // 更新中间表
    let middleDatas: TaskCategoryPerm[] = [];
    if (data.user_ids) {
      let ids = data.user_ids.split(",") as string[];
      ids.forEach((item) => {
        middleDatas.push({
          category_id: result.raw.insertId,
          permission_id: Number(item),
          permission_type: "user",
        });
      });
    }
    if (data.org_ids) {
      let ids = data.org_ids.split(",") as string[];
      ids.forEach((item) => {
        middleDatas.push({
          category_id: result.raw.insertId,
          permission_id: Number(item),
          permission_type: "org",
        });
      });
    }
    if (middleDatas.length > 0) {
      await transactionalEntityManager
        .getRepository(TaskCategoryPerm)
        .insert(middleDatas);
    }
  });
}

// 单个任务分类详情
export async function taskCategoryDetail(category_id: number, user_id: number) {
  let result = await dataSource.getRepository(TaskCategory).findOne({
    relations: {
      taskCategoryPerms: true,
    },
    where: { category_id },
  });

  if (result) {
    return result;
  } else {
    throw new Error("不存在该任务分类！");
  }
}

// 修改任务分类
export async function taskCategoryUpdate(data: any, user_id: number) {
  if (!data.category_id) {
    throw new Error("ID不能为空！");
  }
  const taskCategoryInfo = formatPageFileterData(data, [
    "category_name",
    "category_describe",
    "category_id",
  ]) as unknown as TaskCategory;

  await validatorData(taskCategoryInfo, TaskCategory);

  await dataSource.transaction(async (transactionalEntityManager) => {
    //删除中间表
    await transactionalEntityManager
      .getRepository(TaskCategoryPerm)
      .createQueryBuilder()
      .delete()
      .where("category_id = :category_id", {
        category_id: taskCategoryInfo.category_id,
      })
      .execute();
    // 更新主表
    const updaterESULT = await transactionalEntityManager
      .getRepository(TaskCategory)
      .update(
        {
          category_id: taskCategoryInfo.category_id,
        },
        taskCategoryInfo,
      );
    if (updaterESULT.affected) {
      // 更新中间表
      let middleDatas: TaskCategoryPerm[] = [];
      if (data.user_ids) {
        let ids = data.user_ids.split(",") as string[];
        ids.forEach((item) => {
          middleDatas.push({
            category_id: taskCategoryInfo.category_id,
            permission_id: Number(item),
            permission_type: "user",
          });
        });
      }
      if (data.org_ids) {
        let ids = data.org_ids.split(",") as string[];
        ids.forEach((item) => {
          middleDatas.push({
            category_id: taskCategoryInfo.category_id,
            permission_id: Number(item),
            permission_type: "org",
          });
        });
      }
      if (middleDatas.length > 0) {
        await transactionalEntityManager
          .getRepository(TaskCategoryPerm)
          .insert(middleDatas);
      }
    } else {
      throw new Error("修改失败！");
    }
  });
}

// 根据ids [] 删除任务分类
export async function taskCategoryDelByIds(
  ids: string[],
  user_id: number | string,
) {
  // 删除主表
  await dataSource.getRepository(TaskCategory).delete(ids);
  // 删除关联表
  await dataSource.getRepository(TaskCategoryPerm).delete(ids);
}
